#!/usr/bin/perl6

sub formatPath($path) {
	if ($path ~~ /^\//) {
		return $path;
	}else {
		my $cwd = $*CWD;

		return $cwd ~ '/' ~ $path;
	}
}

sub searchInclude($include, $keyword) {
	my $path = IO::Path.new($include);

	if (!($path.e && $path.r)) {
		return ();
	}

	say '+' x 30 ~ "searching $include";

	my $i-fh = $path.open();

	my @head = ();

	my @lines = $i-fh.lines;

	loop (my $i = 0;$i < @lines;$i++) {
		my $line = @lines[$i];

		if $line ~~ /^\# \s+? include \s? \<(.*)\>/ {
			push @head, $path.dirname ~ "/$0";
			push @head, "/usr/include/$0";
			push @head, "/usr/local/include/$0";
			push @head, "/usr/lib/gcc/x86_64-redhat-linux/4.1.1/include/$0";
		}

		if $line ~~ /$keyword/ {
			"$include:$i  ----+[$line]+".say;		
		}
	}

	return @head;
}

my @searched = ();

multi MAIN($include, $keyword, Bool :s(:$sub-dir) = False){
	my @includes = (formatPath($include));

	loop (;;) {
		my @next = ();

		for @includes -> $file {
			next if any(@searched) eq $file;

			push @searched, $file;

			my @temp = searchInclude($file, $keyword);

			if $sub-dir {
				@next = @next, @temp;
			}
		}

		if (@next != 0) {
			@includes = @next;
		}else{
			last;
		}
	}
}

